package com.mvvm.start.common.mvvm.v.dialog

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.Gravity
import android.view.LayoutInflater
import android.view.WindowManager
import android.widget.LinearLayout
import androidx.databinding.DataBindingUtil
import com.mvvm.start.common.R
import com.mvvm.start.common.databinding.UpdataprogressdialogBinding

class UpDataProgressDialog(context: Context, themeResId: Int) : Dialog(context, themeResId) {
    lateinit var dateBinding: UpdataprogressdialogBinding
    constructor(context: Context) : this(context, R.style.UpDataAppAlertDialog) {
        dateBinding = DataBindingUtil.inflate(
            LayoutInflater.from(context),
            R.layout.updataprogressdialog,
            null,
            false
        )

        setContentView(dateBinding.root)

        val dialogParams: WindowManager.LayoutParams = window!!.attributes
        dialogParams.apply {
            width = WindowManager.LayoutParams.WRAP_CONTENT
            height = WindowManager.LayoutParams.WRAP_CONTENT
            //设置底部显示
            gravity = Gravity.CENTER
//            windowAnimations = R.style.DefaltDialog_Animation
        }
        window!!.attributes = dialogParams
    }

    private val handlers: Handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                1 -> {
                    val bundle = msg.data
                    val progress =
                        Integer.valueOf(bundle.getString("progress")) // 这里的orderid是一个全局变量
                    dateBinding.  tvJindu.text = "$progress%"
                    dateBinding. tvJindu.layoutParams = LinearLayout.LayoutParams(
                        0,
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        progress.toFloat()
                    )
                    dateBinding.  huojian.layoutParams = LinearLayout.LayoutParams(
                        0,
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        (100 - progress).toFloat()
                    )
                }
            }
        }
    }
    /**
     * 设置进度
     */
    fun setProgress(progress: Int) {
        //tv1设置权重是1
        val msg = Message()
        msg.what = 1
        val bundle = Bundle()
        bundle.putString("progress", progress.toString()) // 将服务器返回的订单号传到Bundle中，，再通过handler传出
        msg.data = bundle
        handlers.sendMessage(msg)
    }

    /**
     * 设置标题
     */
    fun setTitle(title: String?) {
        dateBinding.tvTitle.text = title
    }

    /**
     * 设置是否可以取消dialog，由于直接使用setCancelable返回的是Dialog，所以自定义方法
     */
    fun setDialogCancelable(flag: Boolean) {
        setCancelable(flag)
    }


}